﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CMS_GYM.Interface
{
    public partial class frmPhanQuyenNguoiDung : frmTemplete1
    {
        #region "Declare Variables"
        DataTable _dtUsers = new DataTable(), _dtModules = new DataTable(), _dtPhanQuyen = new DataTable();
        //CSQLServer sqlServer = new CSQLServer();
        clsPhanQuyenChucNangBUS PhanQuyenBUS = new clsPhanQuyenChucNangBUS();
        bool UpdateFlag = false;
        int IDQuyenHan;
        #endregion

        #region "Initials"
        #region frmDecentralizationByUsers()
        public frmPhanQuyenNguoiDung()
        {
            InitializeComponent();
            lblTitle.Text = "PHÂN QUYỀN CHO NGƯỜI DÙNG";
            uct_Refresh.Refresh.Click += new EventHandler(btn_Refresh_Click);
            uct_Save.Save.Click += new EventHandler(btn_Save_Click);
            uct_Close.Close.Click += new EventHandler(btn_Close_Click);
            IDQuyenHan = 0;
        }
        #endregion

        private void SetPermission()
        {
            //uct_Reset.Enabled = clsUser.LayThongTinPhanQuyen("PhanQuyenNguoiDung").ChucNang.Them;
            uct_Save.Enabled = clsUser.LayThongTinPhanQuyen("PhanQuyenNguoiDung").ChucNang.Sua;
            //uct_Delete.Enabled = clsUser.LayThongTinPhanQuyen("PhanQuyenNguoiDung").ChucNang.Xoa;
        }

        #region frmDecentralizationByUsers_Load(object sender, EventArgs e)
        private void frmDecentralizationByUsers_Load(object sender, EventArgs e)
        {
            try
            {
                
                lst_QuyenHan.DataSource = null;
                dtg_Modules.DataSource = null;
                _dtModules = new DataTable();
                _dtUsers = new DataTable();
                txt_TotalModules.Text = "Tổng cộng : 0 NSD";
                txt_TotalModules.Text = "Tổng cộng : 0 chức năng - Được sử dụng : 0 chức năng";

                try
                {
                    _dtModules.Columns.Add("STT", typeof(int));
                    _dtModules.Columns.Add("MaChucNang", typeof(int));
                    _dtModules.Columns.Add("TenChucNang", typeof(string));
                    _dtModules.Columns.Add("TrangThai", typeof(int));
                    _dtModules.Columns.Add("ChoPhep", typeof(bool));
                    _dtModules.Columns.Add("Xem", typeof(bool));
                    _dtModules.Columns.Add("Them", typeof(bool));
                    _dtModules.Columns.Add("Xoa", typeof(bool));
                    _dtModules.Columns.Add("Sua", typeof(bool));

                    foreach (DataColumn dc in _dtModules.Columns)
                    {
                        dc.ReadOnly = false;
                        //dc.ReadOnly = (dc.ColumnName != "ChoPhep");
                    }
                    DataTable dtModules = new clsChucNangBUS().LayBang();
                    int totalModules = dtModules.Rows.Count;
                    DataView dvModules = new DataView(dtModules);
                    dvModules.Sort = "TenChucNang";
                    for (int i = 1; i <= totalModules; i++)
                    {
                        DataRowView drv = dvModules[i - 1];
                        _dtModules.Rows.Add(new object[] { i, 
                            drv["MaChucNang"], drv["TenChucNang"], drv["TrangThai"], 
                            false, false, false, false,false });
                    }
                    DataView dv = new DataView(_dtModules);
                    dv.Sort = "STT";
                    dtg_Modules.DataSource = dv;
                    dtg_Modules.Columns["STT"].HeaderText = "STT";
                    dtg_Modules.Columns["TenChucNang"].HeaderText = "Tên chức năng";
                    dtg_Modules.Columns["ChoPhep"].HeaderText = "Cho phép";
                    dtg_Modules.Columns["MaChucNang"].Visible = false;
                    dtg_Modules.Columns["TrangThai"].Visible = false;
                    dtg_Modules.Columns["ChoPhep"].Visible = false;
                    dtg_Modules.Columns["Xem"].HeaderText = "Xem";
                    dtg_Modules.Columns["Them"].HeaderText = "Thêm";
                    dtg_Modules.Columns["Xoa"].HeaderText = "Xóa";
                    dtg_Modules.Columns["Sua"].HeaderText = "Sửa";
                    dtg_Modules.Rows[0].Frozen = true;
                    dtg_Modules_Sorted(null, null);
                    dtg_Modules_Resize(null, null);
                }
                catch { }

                try
                {
                    _dtUsers = new clsQuyenHanBUS().LayBang();
                    DataView dv = new DataView(_dtUsers);
                    dv.Sort = "TenQuyenHan";
                    lst_QuyenHan.DataSource = dv;
                    lst_QuyenHan.DisplayMember = "TenQuyenHan";
                    lst_QuyenHan.ValueMember = "MaQuyenHan";
                    txt_TotalUsers.Text = "Tổng cộng : " + _dtUsers.Rows.Count.ToString() + " NSD";
                }
                catch { }
                SetPermission();
            }
            catch { }
        }
        #endregion
        #endregion

        #region "Events"
        #region btn_Refresh_Click(object sender, EventArgs e)
        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            frmDecentralizationByUsers_Load(null, null);
        }
        #endregion

        #region btn_Save_Click(object sender, EventArgs e)
        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                if (_dtUsers.Rows.Count == 0 || _dtModules.Rows.Count < 2 || IDQuyenHan == 0) return;
                if (MessageBox.Show("Xác nhận cập nhật dữ liệu", "Thông báo", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) return;
                string xml = "<Root>";
                foreach (DataRow dr in _dtModules.Select("STT > 0 and (Xem =1 or Them = 1 or Sua = 1 or Xoa = 1)"))
                {
                    xml += "<Elements MaQuyenHan =\"" + IDQuyenHan.ToString() + "\"" 
                        + " MaChucNang = \"" + dr["MaChucNang"].ToString() + "\""
                        + " Them = \"" + (dr["Them"].ToString().ToLower() == "true" ? "1" : "0") + "\""
                        + " Sua = \"" + (dr["Sua"].ToString().ToLower() == "true" ? "1" : "0") + "\""
                        + " Xoa = \"" + (dr["Xoa"].ToString().ToLower() == "true" ? "1" : "0") + "\"/>";
                }
                xml += "</Root>";
                int result = PhanQuyenBUS.Sua(IDQuyenHan, xml);
                if(result == 1)
                {
                    MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo");
                    UpdateFlag = false;
                    return;
                }
                MessageBox.Show("Lỗi cập nhật dữ liệu", "Thông báo");
            }
            catch
            { MessageBox.Show("Lỗi cập nhật dữ liệu","Thông báo"); }
        }
        #endregion

        #region btn_Close_Click(object sender, EventArgs e)
        private void btn_Close_Click(object sender, EventArgs e)
        {
            if (UpdateFlag)
            {
                if (MessageBox.Show("Bạn có muốn lưu các thay đổi không?", "Thông báo", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                {
                    // KHONG LUU thi THOAT
                    this.Close();
                    return;
                }
                // Muon LUU TRU
                btn_Save_Click(sender, e);
            }
            this.Close();
        }
        #endregion

        #region dtg_Modules_Resize(object sender, EventArgs e)
        private void dtg_Modules_Resize(object sender, EventArgs e)
        {
            try
            {
                dtg_Modules.Columns["STT"].Width = 40;
                dtg_Modules.Columns["Xem"].Width = 50;
                dtg_Modules.Columns["Them"].Width = 50;
                dtg_Modules.Columns["Xoa"].Width = 50;
                dtg_Modules.Columns["Sua"].Width = 50;
                dtg_Modules.Columns["TenChucNang"].Width = dtg_Modules.Width - 260;
            }
            catch { }
        }
        #endregion

        #region lst_Users_SelectedIndexChanged(object sender, EventArgs e)
        private void lst_Users_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                IDQuyenHan = int.Parse(lst_QuyenHan.SelectedValue.ToString());
                if (IDQuyenHan == 0) return;
                DataTable dt = PhanQuyenBUS.LayBang(IDQuyenHan);
                grp_Modules.Text = "D/S Chức năng (" + lst_QuyenHan.Text.Trim() + ")";
                foreach (DataRow dr in _dtModules.Rows)
                {
                    dr["ChoPhep"] = false;
                    dr["Xem"] = false;
                    dr["Them"] = false;
                    dr["Xoa"] = false;
                    dr["Sua"] = false;
                }
                foreach (DataRow dr in dt.Rows)
                {
                    //bool Xem = bool.Parse(dr["Xem"].ToString());
                    ((DataRow)_dtModules.Select("MaChucNang = " + dr["MaChucNang"].ToString()).GetValue(0))["Xem"] = true;
                    bool Them = bool.Parse(dr["Them"].ToString());
                    ((DataRow)_dtModules.Select("MaChucNang = " + dr["MaChucNang"].ToString()).GetValue(0))["Them"] = Them;
                    bool Xoa = bool.Parse(dr["Xoa"].ToString());
                    ((DataRow)_dtModules.Select("MaChucNang = " + dr["MaChucNang"].ToString()).GetValue(0))["Xoa"] = Xoa;
                    bool Sua = bool.Parse(dr["Sua"].ToString());
                    ((DataRow)_dtModules.Select("MaChucNang = " + dr["MaChucNang"].ToString()).GetValue(0))["Sua"] = Sua;
                }
                txt_TotalModules.Text = "Có tổng cộng : " + dt.Rows.Count.ToString() + "/" + Convert.ToString(_dtModules.Rows.Count) + " chức năng được sử dụng";
            }
            catch { }
        }
        #endregion

        #region dtg_Modules_CellMouseUp(object sender, DataGridViewCellEventArgs e)
        private void dtg_Modules_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0) return;
                switch (dtg_Modules.Columns[e.ColumnIndex].Name)
                {
                    case "Xem":
                        dtg_Modules.Rows[e.RowIndex].Cells["Xem"].Value =
                   (dtg_Modules.Rows[e.RowIndex].Cells["Xem"].EditedFormattedValue.ToString().ToLower() ==
                   "true");
                        UpdateFlag = true;
                        break;
                    case "Them":
                        dtg_Modules.Rows[e.RowIndex].Cells["Them"].Value =
                   (dtg_Modules.Rows[e.RowIndex].Cells["Them"].EditedFormattedValue.ToString().ToLower() ==
                   "true");
                        UpdateFlag = true;
                        break;
                    case "Xoa":
                        dtg_Modules.Rows[e.RowIndex].Cells["Xoa"].Value =
                   (dtg_Modules.Rows[e.RowIndex].Cells["Xoa"].EditedFormattedValue.ToString().ToLower() ==
                   "true");
                        UpdateFlag = true;
                        break;
                    case "Sua":
                        dtg_Modules.Rows[e.RowIndex].Cells["Sua"].Value =
                   (dtg_Modules.Rows[e.RowIndex].Cells["Sua"].EditedFormattedValue.ToString().ToLower() ==
                   "true");
                        UpdateFlag = true;
                        break;
                    default:
                        break;
                }
            }
            catch { }
        }
        #endregion

        #region dtg_Modules_KeyDown(object sender, KeyEventArgs e)
        private void dtg_Modules_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if ((e.KeyCode == Keys.Space || e.KeyCode == Keys.Enter) && dtg_Modules.SelectedCells[0].RowIndex == 0 && dtg_Modules.Columns[dtg_Modules.SelectedCells[0].ColumnIndex].Name == "Allow")
                {
                    foreach (DataGridViewRow row in dtg_Modules.Rows)
                    {
                        if (row.Index == 0) continue;
                        row.Cells["Allow"].Value = (dtg_Modules.SelectedCells[0].EditedFormattedValue.ToString().ToLower() == "true");
                    }
                }
            }
            catch { }
        }
        #endregion

        #region dtg_Modules_Sorted(object sender, EventArgs e)
        private void dtg_Modules_Sorted(object sender, EventArgs e)
        {
            try
            {
                dtg_Modules.Rows[0].DefaultCellStyle.BackColor = Color.Silver;
                dtg_Modules.Rows[0].DefaultCellStyle.SelectionBackColor = Color.Silver;
                dtg_Modules.Rows[0].DefaultCellStyle.SelectionForeColor = Color.Black;
                dtg_Modules.Rows[0].DefaultCellStyle.BackColor = Color.Silver;
                dtg_Modules.Rows[0].DefaultCellStyle.ForeColor = Color.Black;
            }
            catch { }
        }
        #endregion

        #region dtg_Modules_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        private void dtg_Modules_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                txt_TotalModules.Text = "Có tổng cộng : " + _dtModules.Select("RecordNumber > 0 and Allow = 1").Length.ToString() + "/" + Convert.ToString(_dtModules.Rows.Count - 1) + " chức năng được sử dụng";
            }
            catch { }
        }
        #endregion

        #region txt_SearchModules_KeyUp(object sender, KeyEventArgs e)
        private void txt_SearchModules_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                DataView dv = (DataView)dtg_Modules.DataSource;
                string search = txt_SearchModules.Text.Trim();
                if (search == string.Empty) dv.RowFilter = string.Empty;
                else dv.RowFilter = "STT = 0 or TenChucNang like '%" + search + "%'";
                dtg_Modules_Sorted(null, null);
            }
            catch { }
        }
        #endregion

        #region txt_SearchUsers_KeyUp(object sender, KeyEventArgs e)
        private void txt_SearchUsers_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                DataView dv = (DataView)lst_QuyenHan.DataSource;
                string search = txt_SearchUsers.Text.Trim();
                if (search == string.Empty) dv.RowFilter = string.Empty;
                else dv.RowFilter = "TenQuyenHan like '%" + search + "%'";
            }
            catch { }
        }
        #endregion
        #endregion
    }
}